<template>
	<view class="page-box">
		<uni-section title="照片上传" type="line"></uni-section>
		<view class="uni-uploader">
			<view class="uni-uploader-body">
				<view class="uni-uploader__files">
					<block v-for="(image,index) in imageList" :key="index">
						<view class="uni-uploader__file">
							<image class="close-box" src="../../static/icon_close.png" mode="aspectFit" @click="cancelImage(index)"></image>
							<image class="uni-uploader__img" mode="aspectFill" :src="image" :data-src="image" @tap="previewImage"></image>
						</view>
					</block>
					<view class="uni-uploader__input-box">
						<view class="uni-uploader__input" @tap="chooseImage"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="big-btn" @click="fnSubmit">下一步</view>
	</view>
</template>
<script>
	import uniSection from '@/components/uni-section/uni-section.vue';
	import permision from "@/common/permission.js"
	import store from '@/store/store.vue'
	var sourceType = [
		['camera'],
		['album'],
		['camera', 'album']
	]
	var sizeType = [
		['compressed'],
		['original'],
		['compressed', 'original']
	]
	export default {
		components: {
			uniSection
		},
		onLoad(option) {			
			this.house = JSON.parse(decodeURIComponent(option.param))	
			this.house.img_url = ''
		},
		data() {
			return {
				house:{},
				pageType: '',//1新房 2二手房 3租房
				title: 'choose/previewImage',
				imageList: [],
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
			}
		},
		onUnload() {
			this.imageList = [],
			this.sourceTypeIndex = 2,
			this.sourceType = ['拍照', '相册', '拍照或相册'],
			this.sizeTypeIndex = 2,
			this.sizeType = ['压缩', '原图', '压缩或原图'],
			this.countIndex = 8;
		},
		methods: {
			cancelImage(index){
				let _this = this
				uni.showModal({
					content: "是否删除该图片？",
					success: (e) => {
						if (e.confirm) {
							console.log("in", index)
							_this.imageList.splice(index, 1)
						} else {
						}
					},
					fail: () => {
					}
				})			
			},
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
				
				// 最多只能有9张图片
				if (this.imageList.length === 9) {
					let isContinue = await this.isFullImg();
					console.log("是否继续?", isContinue);
					if (!isContinue) {
						return;
					}
				}
				let _this = this
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
					success: (res) => {						
						_this.uploadFile(res.tempFilePaths)
					},
					fail: (err) => {
						// #ifdef APP-PLUS
						if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
							this.checkPermission(err.code);
						}
						// #endif
						// #ifdef MP
						uni.getSetting({
							success: (res) => {
								let authStatus = false;
								switch (this.sourceTypeIndex) {
									case 0:
										authStatus = res.authSetting['scope.camera'];
										break;
									case 1:
										authStatus = res.authSetting['scope.album'];
										break;
									case 2:
										authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
										break;
									default:
										break;
								}
								if (!authStatus) {
									uni.showModal({
										title: '授权失败',
										content: 'Hello uni-app需要从您的相机或相册获取图片，请在设置界面打开相关权限',
										success: (res) => {
											if (res.confirm) {
												uni.openSetting()
											}
										}
									})
								}
							}
						})
						// #endif
					}
				})
			},
			isFullImg: function() {
				return new Promise((res) => {
					uni.showModal({
						content: "已经有9张图片了,是否清空现有图片？",
						success: (e) => {
							if (e.confirm) {
								this.imageList = [];
								res(true);
							} else {
								res(false)
							}
						},
						fail: () => {
							res(false)
						}
					})
				})
			},
			previewImage: function(e) {
				var current = e.target.dataset.src
				uni.previewImage({
					current: current,
					urls: this.imageList
				})
			},
			async checkPermission(code) {
				let type = code ? code - 1 : this.sourceTypeIndex;
				let status = permision.isIOS ? await permision.requestIOS(sourceType[type][0]) :
					await permision.requestAndroid(type === 0 ? 'android.permission.CAMERA' :
						'android.permission.READ_EXTERNAL_STORAGE');

				if (status === null || status === 1) {
					status = 1;
				} else {
					uni.showModal({
						content: "没有开启权限",
						confirmText: "设置",
						success: function(res) {
							if (res.confirm) {
								permision.gotoAppSetting();
							}
						}
					})
				}
				return status;
			},
			uploadFile(tempFilePaths){
				let _this = this
				// 单张上传
				console.log(_this.imageList)				
				uni.uploadFile({
					url: store.url + '/image/upload', //仅为示例，非真实的接口地址					
					filePath: tempFilePaths[0],
					name: 'Image',
					formData: {
						//'user': 'test'
					},
					success: (uploadFileRes) => {
						let data = JSON.parse(uploadFileRes.data)
						console.log(data)
						if(data.message == '上传成功'){
							_this.imageList = _this.imageList.concat(tempFilePaths);
							_this.house.img_url += data.url + ';'
						}else{
							uni.showModal({
								content: "图片上传失败",
								success: (e) => {									
								},
								fail: () => {
									res(false)
								}
							})
						}
					}
				});
			},
			fnSubmit() {
				let url = '', _this = this		
				this.house.user_id = getApp().globalData.user_id
				this.house.inviter_id = getApp().globalData.inviter_id	
				switch(parseInt(_this.house.typesOfHouseSource)){
					case 1: 
						url = '/pages/house/publishSaleNew?param=' + encodeURIComponent(JSON.stringify(this.house))
					break;
					case 2:
						this.house.imgUrl = this.house.img_url
						url = '/pages/house/publishSale?param=' + encodeURIComponent(JSON.stringify(this.house))
					break;
					case 3:
						url = '/pages/house/publishMatch?param=' + encodeURIComponent(JSON.stringify(this.house))
					break;
				}
				console.log(this.house.img_url)

				uni.navigateTo({
					url: url
				});		
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page-box {
		padding-bottom: 88rpx;
		box-sizing: border-box;
	
		/deep/ .uni-section {
			margin-top: 0;
			background: #fff;
		}
	
		/deep/ .line {
			background-color: #f13b32;
		}
	}
	
	.uni-common-mt {
		margin-top: 0;
	}
	
	.uni-list::before {
		display: none;
	}
	
	.uni-uploader__file {
		position: relative;
	}
	
	.uni-uploader-body {
		margin-top: 0;
	}
	
	.uni-uploader {
		padding: 20rpx 30rpx;
		background: #FFF;
	}
	
	.close-box {
		position: absolute;
		padding: 20rpx;
		top: -10rpx;
		right: -10rpx;
		width: 40rpx;
		height: 40rpx;
		border-radius: 50%;
		background: #f13b32;
	}
	
	.big-btn {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100%;
		line-height: 88rpx;
		text-align: center;
		color: #fff;
		background: #f13b32;
	}
</style>
